package org.jupiter.blog.common.utils;

import org.apache.commons.lang3.StringUtils;
import org.jupiter.blog.common.constant.SymbolConstant;

import javax.crypto.Cipher;
import java.nio.charset.StandardCharsets;
import java.security.PrivateKey;
import java.util.Base64;
import java.security.MessageDigest;
import java.util.Random;

public class PasswordUtil {

	// 解密前端传来的加密密码
	public static String decryptPassword(String encryptedPassword) throws Exception {
		PrivateKey privateKey = RSAKeyGeneratorUtil.getPrivateKey();
		Cipher cipher = Cipher.getInstance("RSA");
		cipher.init(Cipher.DECRYPT_MODE, privateKey);

		byte[] encryptedBytes = Base64.getDecoder().decode(encryptedPassword);
		byte[] decryptedBytes = cipher.doFinal(encryptedBytes);

		return new String(decryptedBytes, StandardCharsets.UTF_8);
	}

	// 生成盐值
	private static String generateSalt() {
		Random random = new Random();
		byte[] salt = new byte[16];
		random.nextBytes(salt);
		return Base64.getEncoder().encodeToString(salt);
	}

	public static String getHashContent(String content) throws Exception {
		// 使用SHA-256进行哈希
		MessageDigest digest = MessageDigest.getInstance("SHA-256");
		byte[] hashedBytes = digest.digest(content.getBytes(StandardCharsets.UTF_8));

		// 转换为十六进制字符串
		StringBuilder sb = new StringBuilder();
		for (byte b : hashedBytes){
			sb.append(String.format("%02x", b));
		}
		return sb.toString();
	}

	// 对密码进行加盐哈希处理（不可逆）
	public static String hashToDBPassword(String rsaPassword) throws Exception {
		return hashPassword(decryptPassword(rsaPassword));
	}

	// 对密码进行加盐哈希处理（不可逆）
	public static String hashPassword(String password) throws Exception {
		String salt = generateSalt();
		String passwordWithSalt = password + salt;
		// 存储格式: 哈希值$盐值
		return getHashContent(passwordWithSalt) + SymbolConstant.DOLLAR + salt;
	}

	// 验证密码
	public static boolean verifyPassword(String inputPassword, String storedHash) throws Exception {
		String[] parts = StringUtils.split(storedHash, SymbolConstant.DOLLAR);
		if (parts.length != 2){
			return false;
		}
		String hash = parts[0];
		String salt = parts[1];
		// 对输入密码进行同样的哈希处理
		String inputWithSalt = inputPassword + salt;
		return StringUtils.equals(getHashContent(inputWithSalt), hash);
	}
}
